<template>
  <div id="specSignHistory">
    <vxe-toolbar perfect>
      <template #buttons>
        <vxe-form :data="form" title-align="right" title-colon>
          <vxe-form-item title="条码号">
            <template #default="{ data }">
              <vxe-input v-model="data.reqNo" clearable @clear="findSpecSamplingHistoryList()"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="病历号">
            <template #default="{ data }">
              <vxe-input v-model="data.hisReqId" clearable @clear="findSpecSamplingHistoryList()"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="姓名">
            <template #default="{ data }">
              <vxe-input v-model="data.patNa" clearable @clear="findSpecSamplingHistoryList()"></vxe-input>
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item title="病人来源">
              <template #default="{ data }">
                <VxePulldownSelection :url="'/api/his/visit-types'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
                  { field: 'code', title: '编号' },
                  { field: 'name', title: '病人类型' }
                ]" :aimKeys="[
  { targetField: 'visitTypeName', sourceField: 'name' },
  { targetField: 'visitTypeId', sourceField: 'id' }
]" :displayTexts="['name']" :displayTextObj="data.visitTypeName" />
              </template>
            </vxe-form-item> 
             <vxe-form-item title="科室">
              <template #default="{ data }">
                <VxePulldownSelection :url="'/api/hrms/deps'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
                  { field: 'code', title: '编号' },
                  { field: 'name', title: '名称' }
                ]" :aimKeys="[
  { targetField: 'depName', sourceField: 'name' },
  { targetField: 'depId', sourceField: 'id' }
]" :displayTexts="['name']" :displayTextObj="data.depName"
                  :dataObj="{ organizationUnitId: $store.state.userInfo && $store.state.userInfo.employee ? $store.state.userInfo.employee.organizationUnitId : null }" />
              </template>
            </vxe-form-item> -->
          <vxe-form-item title="签收状态">
            <template #default="{ data }">
              <vxe-select v-model="data.isSign" @change="findSpecSamplingHistoryList">
                <vxe-option v-for="(item, index) in signState" :key="index" :value="item.value" :label="item.label"></vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <!-- <vxe-form-item title="接收人">
              <template #default="{ data }">
                <VxePulldownSelection :url="'/api/hrms/employees'" @confirmClick="pulldownSelectConfirm" :tableColumn="[
                  { field: 'code', title: '编号' },
                  { field: 'name', title: '姓名' }
                ]" :aimKeys="[
  { targetField: 'signerName', sourceField: 'name' },
  { targetField: 'signerId', sourceField: 'id' }
]" :displayTexts="['name']" :displayTextObj="data.signerName" :dataObj="{ depId: data.depId }" />
              </template>
            </vxe-form-item> -->

          <vxe-form-item title="接收时间">
            <template #default="{ data }">
              <vxe-input v-model="data.specSignDateS" type="datetime" clearable transfer @clear="findSpecSamplingHistoryList()" @change="findSpecSamplingHistoryList" style="width: 160px"></vxe-input>
              <span class="margin-lr-xs">-</span>
              <vxe-input v-model="data.specSignDateE" type="datetime" clearable transfer @clear="findSpecSamplingHistoryList()" @change="findSpecSamplingHistoryList" style="width: 160px"></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item>
            <template #default>
              <vxe-button class-name="margin-left-sm" icon="vxe-icon-search" type="text" class="button-blue" content="查询" @click="findSpecSamplingHistoryList"></vxe-button>
              <vxe-button icon="vxe-icon-undo" type="text" class="button-red" content="标本退回" @click="returnSpec"></vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>
      </template>
    </vxe-toolbar>

    <div class="specSignHistoryTable" :style="{ height: isChildren ? 'calc(100% - 75px - 65px)' : 'calc(100% - 40px - 32px)' }">
      <vxe-table ref="specSignHistoryTable" v-loading="loading" border align="center" height="auto" :menu-config="tableMenuTop" class="mytable-scrollbar" @menu-click="contextMenuClickEventTop" :data="specSignHistoryList" @cell-click="specSignHistoryRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" resizable show-overflow>
        <vxe-column type="seq" width="26"></vxe-column>
        <vxe-column field="state" title="是否上机" width="80px" align="center">
          <template #default="{ row }">
            <span :class="row.isRegistrant ? 'text-blue' : 'text-red'">
              {{ row.state === '80' ? '是' : '否' }}
            </span>
          </template>
        </vxe-column>
        <vxe-column field="registrationTime" title="上机日期" width="120"></vxe-column>
        <!-- <vxe-column field="wtName" title="工作组" width="100"></vxe-column> -->
        <vxe-column field="patType" title="病人来源" width="60">
          <template #default="{ row }">
            {{
              row.patType === '1'
              ? '门诊'
              : row.patType === '2'
                ? '急诊'
                : row.patType === '3'
                  ? '住院'
                  : row.patType === '4'
                    ? '体检'
                    : '未知'
            }}
          </template>
        </vxe-column>
        <vxe-column field="sampleTypeNa" title="类型" width="60"></vxe-column>
        <vxe-column field="reqNo" title="条码号" width="100px">
          <template #default="{ row }">
            <span>{{ row.reqNo ? row.reqNo : '' }}</span>
          </template>
        </vxe-column>

        <vxe-column field="dep" title="申请科室" width="80">
          <template #default="{ row }">
            <span>{{ row.reqDeptNa ? row.reqDeptNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="hisReqId" title="申请号" width="80"></vxe-column>
        <vxe-column field="isSign" title="接收状态" width="80px" align="center">
          <template #default="{ row }">
            <span :class="row.isSign ? 'text-blue' : 'text-red'">
              {{ row.isSign === 1 ? '已接收' : '未接收' }}
            </span>
          </template>
        </vxe-column>
        <!-- <vxe-column field="isOriginal" title="是否原始标本" width="100px" align="center">
          <template #default="{ row }">
            <span :class="row.spec.isOriginal ? 'text-blue' : 'text-red'">
              {{ row.spec.isOriginal ? '是' : '否' }}
            </span>
          </template>
        </vxe-column> -->
        <!-- <vxe-column field="date" title="传送方式" width="100"></vxe-column> -->
        <vxe-column field="patNo" title="病历号" width="100"></vxe-column>
        <vxe-column field="patNa" title="姓名" width="80"></vxe-column>
        <vxe-column field="sex" title="性别" width="60"></vxe-column>
        <vxe-column field="age" title="年龄" width="80"></vxe-column>
        <vxe-column field="bedNo" title="床号" width="80"></vxe-column>
        <vxe-column field="feeName" title="申请项目" width="180"></vxe-column>
        <vxe-column field="reqDoctorNa" title="申请人" width="80">
          <template #default="{ row }">
            <span>{{ row.reqDoctorNa ? row.reqDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="reqTime" title="申请时间" width="120">
          <template #default="{ row }">
            <span>{{ row.reqTime ? row.reqTime : '' }}</span>
          </template>
        </vxe-column>

        <vxe-column field="signerNa" title="接收人" width="80">
          <template #default="{ row }">
            <span>{{ row.signerNa ? row.signerNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="signTime" title="接收时间" width="120">
          <template #default="{ row }">
            <span>{{ row.signTime ? row.signTime : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingDoctorNa" title="采集人" width="80">
          <template #default="{ row }">
            <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
          </template>
        </vxe-column>
        <vxe-column field="samplingTime" title="采集时间" min-width="120">
          <template #default="{ row }">
            <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
          </template>
        </vxe-column>
      </vxe-table>
      <vxe-pager align="left" min-height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="[
          'PrevJump',
          'PrevPage',
          'Number',
          'NextPage',
          'NextJump',
          'Sizes',
          'FullJump',
          'Total'
        ]" @page-change="handleSizeChange($event)"></vxe-pager>
    </div>

    <vxe-modal v-model="returnReasonModule" width="760px" height="calc(100% - 60px)" show-footer destroy-on-close :position="{ top: 50 }" className="returnModal mytable-scrollbar">
      <template #title>
        <span style="color: red">{{ title }}</span>
      </template>
      <template #default>
        <UnqualifiedSpecRec ref="unqualifiedSpecRecRef" @chackedReasonChange="chackedReasonChange" />
      </template>
      <template #footer>
        <div class="flex justify-end padding-right-xs">
          <vxe-button class-name="margin-left-sm" content="取消" @click="returnReasonModule = false"></vxe-button>
          <vxe-button class-name="margin-left-sm" status="primary" content="确定" @click="confirmReturnSpec"></vxe-button>
        </div>
      </template>
    </vxe-modal>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { onMounted, ref, reactive, getCurrentInstance } from 'vue';
import { VXETable } from 'vxe-table';
import { AppStore } from '../../../stores/store';
import { IsEmpty, formatDateTime } from '@/utils/common';
import XEClipboard from 'xe-clipboard';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
import UnqualifiedSpecRec from '@/components/UnqualifiedSpecRec.vue';

// 全局变量定义区 ==========
let tableMenuTop = {
  className: 'my-menus',
  body: {
    options: [
      [
        {
          code: 'copy',
          name: '复制内容',
          prefixIcon: 'vxe-icon-copy',
          className: 'my-copy-item',
          visible: false
        }
      ]
    ]
  },
  visibleMethod: ({ options, column }) => {
    const isVisible = column && column.field === 'specCode';
    options.forEach((list) => {
      list.forEach((item) => {
        if (column) {
          if (item.code === 'copy') {
            item.visible = isVisible;
          }
        } else {
          item.visible = false;
        }
      });
    });
    return true;
  }
};
let pageIndex = 1;
let totalCount = 0;
let loading = ref(false);
let specSignHistoryList = reactive([]); //列表
//let currentSpecSignHistory = {} as any; //当前选中行
let currentRowIndex = 0;
let { proxy }: any = getCurrentInstance();
let signState = [
  { value: null, label: '全部' },
  {
    value: true,
    label: '已接收'
  },
  {
    value: false,
    label: '未接收'
  }
];
let returnReasonModule = ref(false);
let returnReason = '';
let form = reactive({
  patId: '', //病历号
  reqNo: '',
  patNa: '',
  specSignDateS: formatDateTime(new Date(), 'yyyy-MM-dd 00:00:00'),
  specSignDateE: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});

// 方法定义区 =============
onMounted(() => {
  findSpecSamplingHistoryList();
});
let unqualifiedDetailIds = reactive({})
function chackedReasonChange(val: any) {
  unqualifiedDetailIds = val;
  // console.log('---------unqualifiedDetailIds-------:', unqualifiedDetailIds.value);
}
//获取列表
function findSpecSamplingHistoryList() {
  specSignHistoryList.length = 0;
  loading.value = true;
  const url = '/lab/reqMain/findLabReqMainPageListByState';
  const data = {
    state: '70',
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    patId: !IsEmpty(form.patId) ? form.patId : null,
    reqNo: !IsEmpty(form.reqNo) ? form.reqNo : null,
    patNa: !IsEmpty(form.patNa) ? form.patNa : null,
    samplingTimeS: !IsEmpty(form.specSignDateS) ? form.specSignDateS : null,
    samplingTimeE: !IsEmpty(form.specSignDateE) ? form.specSignDateE : null
  };

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      specSignHistoryList.push(...res.data.records);
      page.totalResult = res.data.total;
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      proxy.$alert(err, '提示');
    });
}
let currentSpecSignHistory = reactive({
  id: '',
  reqNo: '',
  hisReqId: '',
  patId: '',
  patNa: '',
  sex: '',
  isSign: '',
  feeName: ''
}); //当前采集记录详情


let unqualifiedSpecRecRef: any = ref(null); //检验仪器基本信息表单ref
let currentRow = reactive({});
let title = ref('');
// 行点击事件
function specSignHistoryRowClick({ row, rowIndex }) {
  currentRow = row;
  title.value = '【患者姓名】 ' + currentRow.patNa + '  【申请项目】' + currentRow.feeName

  // UnqualifiedSpecRecRef.value?.initPage(row); //传递给右侧基本信息表单
  // console.log('实例',UnqualifiedSpecRecRef)
  currentRowIndex = rowIndex;
  Object.assign(currentSpecSignHistory, row);
  (proxy.$refs.specSignHistoryTable as any).setCurrentRow(row);
}
//右键菜单
function contextMenuClickEventTop({ menu, row, column }) {
  switch (menu.code) {
    case 'copy':
      if (row && column) {
        const a = 'spec';
        if (XEClipboard.copy(row[a][column.property])) {
          VXETable.modal.message({ content: '已复制到剪贴板！', status: 'success' });
        }
      }
      break;
    default:
      VXETable.modal.message(`点击了 ${menu.name} 选项`);
  }
}
//  标本退回
function returnSpec() {
  if (!currentSpecSignHistory || IsEmpty(currentSpecSignHistory.id)) {
    VxeMessage('请先选择退回标本', VxeNotifyType.error);
    return;
  }
  returnReasonModule.value = true;
  proxy.$nextTick(() => {
    unqualifiedSpecRecRef.value.initPage(currentRow)
  })
}

function confirmReturnSpec() {
  if (unqualifiedDetailIds.length == 0 || IsEmpty(unqualifiedDetailIds)) {
    VxeMessage('请选择回退原因', VxeNotifyType.error);
    return;
  }
  loading.value = true;
  //当前登录用户 EmpId
  const url = '/lab/req/unqualified/detail/saveDetail';
  const data = {
    reqNo: currentRow.reqNo,
    unqualifiedDetailIds: unqualifiedDetailIds
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 200) {
        VxeMessage('操作成功', VxeNotifyType.success);
        findSpecSamplingHistoryList();
        returnReasonModule.value = false;
      } else {
        loading.value = false;
        VxeMessage('操作失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('操作失败', VxeNotifyType.error);
    });
}

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
//点击每页数量
function handleSizeChange({ type, currentPage, pageSize }) {
  console.log('pagesizeChange', type, currentPage, pageSize);
  if (type == 'size') {
    page.pageSize = pageSize;
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  findSpecSamplingHistoryList();
}

//下拉选择列表
function pulldownSelectConfirm(e) {
  e.aimKeys.forEach((item) => {
    form[item.targetField] = e.row[item.sourceField];
  });
  findSpecSamplingHistoryList();
}
</script>
<style lang="scss" scoped>
#specSignHistory {
  height: 100%;

  .vxe-form {
    :deep(.vxe-form--item) {
      margin-right: 10px;
    }
  }

  .specSignHistoryTable {
    height: calc(100vh - 40px - 32px);
  }

  .returnModal {
    :deep(.vxe-modal--body) {
      height: calc(100% - 37px);
    }
  }
}

:deep(.vxe-textarea-height > textarea) {
  height: calc(40vh - 10px) !important;
}
</style>
